package com.siwei.mes.common.exception.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotSafeException;
import com.siwei.mes.common.exception.BizException;
import com.siwei.mes.common.exception.RepositoryException;
import com.siwei.mes.common.result.Json;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @Description: 全局异常处理类
 * @Version: 1.0
 * @author: chenmaolin
 * @date: 2021-12-08
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final static String NORMAL_EXCEPTION = "10000:系统繁忙，请重试";
    private final static String SEPARATOR = ":";

    /**
     * 报错默认走的异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Throwable.class)
    public Json defaultException(Exception ex) {
        printStackTraceInfo(ex);
        return Json.fail().msg(ex.getMessage());
    }

    /**
     * 空指针
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(NullPointerException.class)
    public Json defaultException(NullPointerException ex) {
        printStackTraceInfo(ex);
        return Json.fail().msg("空指针异常,需要后台人工处理!");
    }

    /**
     * 打印异常栈追踪的信息
     *
     * @param ex 追踪到的栈异常信息集合
     */
    private void printStackTraceInfo(Exception ex) {
        log.error("追踪栈异常信息：" + ex);
        StackTraceElement[] stackTraceElements = ex.getStackTrace();
        for (StackTraceElement stackTraceElement : Optional.ofNullable(stackTraceElements).orElse(new StackTraceElement[0])) {
            String errMsg = String.valueOf(stackTraceElement);
            /**只打印此项目业务中捕捉到的异常信息*/
            if (errMsg.contains("com.siwei.mes")) {
                log.error(errMsg);
            }
        }
    }

    /**
     * 自定义 BizException异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BizException.class)
    public Json bizException(BizException ex) {
//        printStackTraceInfo(ex);
        if (StringUtils.isBlank(ex.getErrCode()) || StringUtils.isBlank(ex.getErrMsg())) {
            log.error(ex.getLocalizedMessage());
            return Json.fail(100000, ex.getLocalizedMessage());
        }
        log.error(ex.getErrMsg());
        return Json.fail(Integer.parseInt(ex.getErrCode()), ex.getErrMsg());
    }


    @ResponseBody
    @ExceptionHandler(RepositoryException.class)
    public Json repositoryException(RepositoryException ex) {
        printStackTraceInfo(ex);
        if (StringUtils.isBlank(ex.getErrCode()) || StringUtils.isBlank(ex.getErrMsg())) {
            return Json.fail(100000, ex.getLocalizedMessage());
        }
        return Json.fail(Integer.parseInt(ex.getErrCode()), ex.getErrMsg());
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Json methodArguemtValidException(MethodArgumentNotValidException ex) {
        log.error("^methodArguemtValidException_error_^:" + ex);
        return getValidatorErrResult(ex.getBindingResult());
    }

    @ResponseBody
    @ExceptionHandler(BindException.class)
    public Json bindException(BindException ex) {
        log.error("^bindException_error_^:" + ex);
        return getValidatorErrResult(ex.getBindingResult());
    }

    /**
     * 返回错误信息
     *
     * @param bindingResult
     * @return
     */
    private Json getValidatorErrResult(BindingResult bindingResult) {
        Json resp = null;
        try {
            resp = Optional.ofNullable(bindingResult.getFieldError())
                    .map(msg -> MessageHandler.getMessage(msg.getDefaultMessage()))
                    .map(errMsg -> Json.fail(Integer.parseInt(errMsg[0]), errMsg[1]))
                    .orElseGet(() -> {
                        String[] err = MessageHandler.NORMAL_EXCEPTION.split(SEPARATOR);
                        return Json.fail(Integer.parseInt(err[0]), err[1]);
                    });
        } catch (Exception e1) {
            log.error("^_error_^:" + e1);
            String[] errMsg = NORMAL_EXCEPTION.split(SEPARATOR);
            log.error(errMsg[1]);
            resp = Json.fail(Integer.parseInt(errMsg[0]), errMsg[1]);
        }
        return resp;
    }

    /**
     * saToken未登录
     *
     * @param nle
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @ExceptionHandler(NotLoginException.class)
    public Json handlerNotLoginException(NotLoginException nle, HttpServletResponse response) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        String message = null;
        // 判断场景值，定制化异常信息
        if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "当前会话未登录";
        } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "登录已过期，请重新登录";
        } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "登录已过期，请重新登录";
        } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "该账号已异地登录，请重新登录";
        } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "异地登录，系统强制退出！";
        } else {
            message = nle.getMessage();
        }
        String[] msg = MessageHandler.getMessage(message);
        return Json.fail(Integer.parseInt(msg[0]), msg[1]);
    }

    /**
     * 二级认证异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(NotSafeException.class)
    public Json handlerNotSafeException(NotSafeException e) {
        return Json.fail().msg(e.getMessage());
    }
}
